package com.hangwei.aicabinet.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.support.annotation.NonNull;
import android.view.Display;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 魏学军 on 2016/12/10.
 */

public class Tools {

    private final static double EARTH_RADIUS = 6378137.0;
    private static String IMEI = null;
    private static Context mContext;
    private static Boolean isDebug = null;

//    public static String getIMEI() {
//        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Service.TELEPHONY_SERVICE);
//        IMEI = tm.getDeviceId();
//        if (TextUtils.isEmpty(IMEI)) {
//            IMEI = UUID.randomUUID().toString();
//        }
//        return IMEI;
//    }

    public static void init(Context context) {
        synIsDebug(context);
        mContext = context;
    }

    public static Context getContext() {
        if (mContext == null) {
            throw new RuntimeException("Mode模块没有初始化");
        }
        return mContext;
    }

    /**
     * 获取版本名
     *
     * @return
     */
    public static String getVersionName() {
        String versionName = "";
        if (mContext != null) {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = null;
            try {
                pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            versionName = pi.versionName;
        }
        return versionName;
    }

//    /**
//     * 设置图片
//     * @param simpleDraweeView
//     * @param url
//     */
//    public static void setImage(SimpleDraweeView simpleDraweeView,String url){
//        if(!TextUtils.isEmpty(url)){
//            simpleDraweeView.setImageURI(Uri.parse(url));
//        }else{
//            simpleDraweeView.setImageURI(Uri.EMPTY);
//        }
//    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode() {
        int versionCode = 0;
        if (mContext != null) {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = null;
            try {
                pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            versionCode = pi.versionCode;
        }
        return versionCode;
    }

    /**
     * 获取屏幕宽度和高度
     */
    public static int[] getScreenSize() {
        int[] size = new int[2];
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point outSize = new Point();
        display.getSize(outSize);
        size[0] = outSize.x;
        size[1] = outSize.y;
        return size;
    }

    /**
     * 验证手机号格式
     *
     * @return
     */
    public static boolean checkPhoneFormat(String num) {
        boolean flag = true;
        try {
            //长度小于11位
            if (num.length() < 11) {
                return false;
            }
            //首位不为1
            if (num.indexOf("1") != 0) {
                return false;
            }
//            String check =  "^((10[0-9])|(13[0-9])|(15[^4,\\D])|(14[57])|(17[0,0-9])|(18[0,0-9]))\\d{8}$";
//            Pattern regex = Pattern.compile(check);
//            Matcher matcher = regex.matcher(num);
//            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 关闭软键盘
     *
     * @param context
     * @param editText
     */
    public static void closeSoftInputFromWindow(Context context, EditText editText) {
        InputMethodManager m = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        m.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    /**
     * 对double数据进行取精度, 保留2位小数, 精度取值方式 BigDecimal.ROUND_HALF_UP
     *
     * @param value double数据
     * @return 精度计算后的数据
     */
    public static double round(double value) {
        return round(value, 2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 对double数据进行取精度
     *
     * @param value        double数据
     * @param scale        精度位数(保留的小数位数)
     * @param roundingMode 精度取值方式
     * @return 精度计算后的数据
     */
    public static double round(double value, int scale, int roundingMode) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(scale, roundingMode);
        double d = bd.doubleValue();
        bd = null;
        return d;
    }

    //字符串转指定格式时间
    public static String getMyDate(String str) {
        return stringToDate(str, "yyyy-MM-dd", "yyyy/MM/dd");
    }

    /**
     * 字符串转指定格式时间
     *
     * @param dateStr
     * @param dateFormatStr
     * @param formatStr
     * @return
     */
    public static String stringToDate(String dateStr, String dateFormatStr, String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormatStr);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat s = new SimpleDateFormat(formatStr);

        return s.format(date);
    }

    /**
     * 倒计时
     *
     * @param time 毫秒
     * @return
     */
    public static String getCountDown(long time) {
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long hour = time / nh;// 计算差多少小时
        long min = time % nh / nm;// 计算差多少分钟
        long sec = time % nh % nm / ns;// 计算差多少秒
        StringBuilder sb = new StringBuilder();
        if (hour < 10) {
            sb.append("0");
        }
        sb.append(hour);
        sb.append(":");
        if (min < 10) {
            sb.append("0");
        }
        sb.append(min);
        sb.append(":");
        if (sec < 10) {
            sb.append("0");
        }
        sb.append(sec);
        return sb.toString();
    }

    /**
     * sp转px
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * convert dp to its equivalent px
     * <p>
     * 将dp转换为与之相等的px
     */
    public static int dp2px(Context context, float dipValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static double gps2m(double lat_a, double lng_a, double lat_b, double lng_b) {
        double radLat1 = (lat_a * Math.PI / 180.0);
        double radLat2 = (lat_b * Math.PI / 180.0);
        double a = radLat1 - radLat2;
        double b = (lng_a - lng_b) * Math.PI / 180.0;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    public static String sub(String value1, String value2) {
        try {
            return String.valueOf(Integer.valueOf(value1) - Integer.valueOf(value2));
        } catch (Exception e) {
        }
        BigDecimal b1 = new BigDecimal(value1);
        BigDecimal b2 = new BigDecimal(value2);
        return String.valueOf(b1.subtract(b2).doubleValue());
    }

    /**
     * 浮点数取整，如15.00 就为15
     *
     * @param num
     * @return
     */
    public static String formatInteger(Object num) {
        BigDecimal bigDecimal = null;
        if (num instanceof String) {
            bigDecimal = new BigDecimal((String) num);
        } else if (num instanceof Double) {
            bigDecimal = new BigDecimal((Double) num);
        } else {
            return "";
        }
        if (bigDecimal.doubleValue() == bigDecimal.intValue()) {
            return String.valueOf(bigDecimal.intValue());
        } else {
            return String.valueOf(bigDecimal.doubleValue());
        }
    }

    /**
     * 格式化金钱为人民币显示 #,###.##
     *
     * @param money
     * @return
     */
    public static String formartRMB(String money) {
        NumberFormat nf = new DecimalFormat("#,###.##");
        String sfMoney = "￥" + nf.format(Double.valueOf(money));
        return sfMoney;
    }

    /**
     * 将yyyy-MM-dd 转换成yyyy/MM/dd格式
     *
     * @param time
     * @return
     */
    public static String getFormatDateBySlash(String time) {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = "";
        try {
            formatDate = new SimpleDateFormat("yyyy/MM/dd").format(sdf.parse(time));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formatDate;
    }

    /**
     * 距离格式化
     *
     * @param distance
     * @return
     */
    public static String formatDistance(String distance) {
        try {
            double tmp = Double.parseDouble(distance);
            if (tmp > 1000 * 50) {
                return ">50km";
            }
            if (tmp >= 1000) {
                return String.format("%.1f", tmp / 1000) + "km";
            }
            return distance + "m";
        } catch (Exception e) {
        }
        return null;
    }

    public static boolean isDebug() {
        return isDebug != null && isDebug;
    }

    private static void synIsDebug(Context context) {
        if (isDebug == null) {
            isDebug = context.getApplicationInfo() != null &&
                    (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        }
    }

    public static void gotoMap(Context context, String latitude, String longitude, String schoolName) {
        PackageInfo info = PackageM.getInstalledPackage(mContext, "com.baidu.BaiduMap");
        if (info != null) {
            try {
                Intent intent = Intent.getIntent("intent://map/direction?destination=latlng:" + latitude + "," + longitude + "|name:" + schoolName + "&mode=driving&#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent); //启动调用
            } catch (URISyntaxException e) {

            }
            return;
        }
        info = PackageM.getInstalledPackage(mContext, "com.autonavi.minimap");
        if (info != null) {
            try {
                Intent intent = Intent.getIntent("androidamap://navi?sourceApplication=" + "&poiname=" + schoolName + "&lat=" + latitude + "&lon=" + longitude + "&dev=0");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (URISyntaxException e) {

            }
            return;
        }
        Toast.makeText(mContext, "请安装百度或高德地图", Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取String的MD5值
     *
     * @param info 字符串
     * @return 该字符串的MD5值
     */
    public static String getMD5(String info) {
        try {
            //获取 MessageDigest 对象，参数为 MD5 字符串，表示这是一个 MD5 算法（其他还有 SHA1 算法等）：
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            //update(byte[])方法，输入原数据
            //类似StringBuilder对象的append()方法，追加模式，属于一个累计更改的过程
            md5.update(info.getBytes("UTF-8"));
            //digest()被调用后,MessageDigest对象就被重置，即不能连续再次调用该方法计算原数据的MD5值。可以手动调用reset()方法重置输入源。
            //digest()返回值16位长度的哈希值，由byte[]承接
            byte[] md5Array = md5.digest();
            //byte[]通常我们会转化为十六进制的32位长度的字符串来使用,本文会介绍三种常用的转换方法
            return bytesToHex1(md5Array);
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    @NonNull
    private static String bytesToHex1(byte[] md5Array) {
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < md5Array.length; i++) {
            int temp = 0xff & md5Array[i];//TODO:此处为什么添加 0xff & ？
            String hexString = Integer.toHexString(temp);
            if (hexString.length() == 1) {//如果是十六进制的0f，默认只显示f，此时要补上0
                strBuilder.append("0").append(hexString);
            } else {
                strBuilder.append(hexString);
            }
        }
        return strBuilder.toString();
    }

}